<?php

namespace app\common\model\Product;

use think\Model;

// 软删除的模型
use traits\model\SoftDelete;

/**
* 商品模型
*/

class Product extends Model
 {
    //继承软删除
    use SoftDelete;

    //模型对应的是哪张表
    protected $table = 'pre_product';

    //开启自动写入
    protected $autoWriteTimestamp = true;

    //设置字段的名字
    protected $createTime = 'createtime';

    //禁止 写入的时间字段
    protected $updateTime = false;

    // 软删除的字段
    protected $deleteTime = 'deletetime';

    //如果想要在查询的时候显示出，获取器自定义的字段
    protected $append = [
        'thumbs_cdn', //多张
        'cover_cdn', //单张
    ];

    //图片字段的验证器  thumbs_cdn

    public function getThumbsCdnAttr( $value, $data ) {
        //获取的是 config.php 当中 cdn选项
        $cdn = config( 'cdn' );

        // $thumbs = empty( $data[ 'thumbs' ] ) ? [] : explode( ',', $data[ 'thumbs' ] );
        $thumbs = empty( $data[ 'thumbs' ] ) ? [] : trim( $data[ 'thumbs' ] );

        if ( empty( $thumbs ) ) {
            return [];
        }

        //字符串替换
        // uploads/20211015/1.jpg, http://www.ask.com/uploads/20211015/1.jpg,
        // uploads/20211015/2.jpg,
        // uploads/20211015/3.jpg

        $thumbs = str_replace( 'uploads/', $cdn.'/uploads/', $thumbs );

        //在转换为数组
        $list = explode( ',', $thumbs );

        return $list;
    }

    public function getCoverCdnAttr( $value, $data ) {
        //获取的是 config.php 当中 cdn选项
        $cdn = config( 'cdn' );

        // $thumbs = empty( $data[ 'thumbs' ] ) ? [] : explode( ',', $data[ 'thumbs' ] );
        $thumbs = empty( $data[ 'thumbs' ] ) ? [] : trim( $data[ 'thumbs' ] );

        if ( empty( $thumbs ) ) {
            return [];
        }

        //字符串替换
        $thumbs = str_replace( 'uploads/', $cdn.'/uploads/', $thumbs );

        //在转换为数组
        $list = explode( ',', $thumbs );

        if ( count( $list ) > 0 ) {
            return $list[ 0 ];
        } else {
            return $cdn.'/assets/admin/images/product.jpg';
        }
    }

    //关联查询

    public function type() {
        return $this->belongsTo( 'app\common\model\Product\Type', 'typeid', 'id', [], 'LEFT' )->setEagerlyType( 0 );
    }

    public function vip() {
        return $this->belongsTo( 'app\common\model\Product\Vip', 'id', 'proid', [], 'LEFT' )->setEagerlyType( 0 );
    }
}
